package com.fly.data.jdbc.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TaskService
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    /**
     * 指定使用自定义线程池,启用事务
     */
    @Async("taskExecutor")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void asyncTask1(String taskName)
    {
        try
        {
            TimeUnit.MILLISECONDS.sleep(1000L); // 模拟耗时操作
            jdbcTemplate.update("INSERT INTO user(user_name, age) VALUES(?, ?)", "test1", System.currentTimeMillis() % 50);
            int i = 8 / 0;
            log.info("[{}] 完成任务:{}", Thread.currentThread().getName(), taskName);
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            throw new RuntimeException("任务中断", e);
        }
    }
    
    /**
     * 指定使用自定义线程池,不启用事务
     */
    @Async("taskExecutor")
    public void asyncTask2(String taskName)
    {
        try
        {
            TimeUnit.MILLISECONDS.sleep(1000L); // 模拟耗时操作
            jdbcTemplate.update("INSERT INTO user(user_name, age) VALUES(?, ?)", "test1", System.currentTimeMillis() % 50);
            int i = 8 / 0;
            log.info("[{}] 完成任务:{}", Thread.currentThread().getName(), taskName);
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            throw new RuntimeException("任务中断", e);
        }
    }
    
    /**
     * 指定使用自定义线程池,不启用事务
     */
    public List<Map<String, Object>> query()
    {
        return jdbcTemplate.queryForList("SELECT * FROM user");
    }
}